using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using System.Management.Automation;

namespace Community.SharePoint.Commands
{
    [Cmdlet(VerbsCommon.Remove, "Web", 
        SupportsShouldProcess = true, 
        ConfirmImpact=ConfirmImpact.Medium)]
    
    public class RemoveWebCommand : WebBaseCommand
    {
      

        [Parameter]
       public SwitchParameter Force
        {
            get { return _force; }
            set { _force = value; }
        }

        protected override void ProcessRecord()
        {
            Reverse = true;
            foreach (SPWeb web in MatchingWebs())
            {

                if (!this.ShouldProcess(web.Url, "Deleting") && !_force)
                {
                    continue;
                }

                if (web.Webs.Count > 0)
                {
                    WriteDebug(string.Format("{0} has {1} sub webs.", web.Url, web.Webs.Count));
                    System.Exception ex = new Exception(string.Format("Cannot delete web with children webs. URL: {0}", web.Url));

                    WriteError(new ErrorRecord(
                               ex,
                               "Delete web failed.",
                               ErrorCategory.InvalidOperation,
                               web.Url));
                    continue;
                }

                if (web.IsRootWeb)
                {
                    WriteDebug(string.Format("{0} is a root web. Cannot delete a root web using Remove-Web",web.Url));
                  
                    System.Exception ex = new Exception(string.Format("Cannot delete root web. Use Remove-Site instead.  URL: {0}", web.Url));

                    WriteError(new ErrorRecord(
                               ex,
                               "Delete web failed.",
                               ErrorCategory.InvalidOperation,
                               web.Url));
                    continue;

                }
                try
                {
                    WriteVerbose(string.Format("Deleting web:{0}", web.Url));
                    WriteVerbose(string.Format("Deleting web:{0}", web.Url));
                    web.Delete();
                }
                catch (Exception Ex)
                {
                    WriteError(new ErrorRecord(
                        Ex,
                        "Remove-Web Failed.",
                        ErrorCategory.InvalidOperation,
                        web.Url));
                }
            }
        }
    }
}
 